<template>
  <div class="container-item-resource-create">
    <input type="file" @change="uploadHandler">
    <el-form label-width="80px" label-opsition="left" size="mini">
      <el-form-item label="资源名称">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="资源后缀">
        <span>{{ formData.suffix }}</span>
      </el-form-item>
      <el-form-item label="资源大小">
        <span>{{ formData.size }}</span>
      </el-form-item>
      <el-form-item label="资源类型">
        <span>{{ formData.mime }}</span>
      </el-form-item>
      <el-form-item label="sha256">
        <span>{{ formData.sha256 }}</span>
      </el-form-item>
      <el-form-item>
        <el-button @click="upload">上传</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// utils
import { ossPutUpload } from '@/utils/upload_handler_miva';
import sha256 from 'crypto-js/sha256';
// api
import { saveResource } from '@/api/mivawork/resource.js';

export default {
  data() {
    return {
      file: null,
      formData: {
        name: '',
        size: null,
        mime: '',
        suffix: '',
        sha256: '',
        url: ''
      }
    };
  },
  methods: {
    uploadHandler(evt) {
      const file = evt.target.files[0];
      this.file = file;
      this.formData.name = file.name.slice(0, file.name.lastIndexOf('.'));
      this.formData.suffix = file.name.slice(file.name.lastIndexOf('.') + 1);
      this.formData.size = file.size;
      this.formData.mime = file.type;
      this.formData.sha256 = sha256(file).toString();
    },
    async upload() {
      if (!this.file) {
        this.$message('请先选择资源');
        return;
      }
      const res_uoload = await ossPutUpload({
        file: this.file,
        name: `${this.formData.sha256}.${this.formData.suffix}`,
        dir: this.formData.suffix + '/'
      });
      this.formData.url = res_uoload.name;
      await saveResource(this.formData);
      this.$emit('upload');
    }
  }
};
</script>
